"""知识图谱配置设置"""
import os
from pydantic import Field, model_validator
from pydantic_settings import BaseSettings, SettingsConfigDict
from dotenv import load_dotenv

load_dotenv()

class KnowledgeGraphSettings(BaseSettings):
    """知识图谱配置类"""
    
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        case_sensitive=False,
        extra="ignore",
        env_prefix="KNOWLEDGE_GRAPH_"
    )
    
    # Neo4j图数据库配置
    neo4j_uri: str = Field(default=os.getenv("KNOWLEDGE_GRAPH_NEO4J_URI", ""), description="Neo4j数据库连接URI")
    neo4j_user: str = Field(default=os.getenv("KNOWLEDGE_GRAPH_NEO4J_USER", ""), description="Neo4j用户名")
    neo4j_password: str = Field(default=os.getenv("KNOWLEDGE_GRAPH_NEO4J_PASSWORD", ""), description="Neo4j密码（必须通过环境变量设置）")
    
    # 嵌入模型配置
    embedding_model: str = Field(default=os.getenv("KNOWLEDGE_GRAPH_EMBEDDING_MODEL", ""), description="句子嵌入模型名称")
    
    # 向量搜索配置
    faiss_index_dim: int = Field(default=384, description="FAISS向量索引维度")
    search_limit: int = Field(default=5, description="知识图谱查询结果限制")
    
    # 知识提取配置
    min_entity_length: int = Field(default=3, description="最小实体长度")
    
    # Transformers离线模式
    transformers_offline: bool = Field(
        default=False,
        description="Transformers库是否在离线模式下运行"
    )

    @model_validator(mode='after')
    def validate_knowledge_graph_settings(self) -> 'KnowledgeGraphSettings':
        """验证知识图谱配置"""
        if not self.neo4j_uri:
            raise ValueError("KNOWLEDGE_GRAPH_NEO4J_URI不能为空，请在.env文件中设置")
        if not self.neo4j_user:
            raise ValueError("KNOWLEDGE_GRAPH_NEO4J_USER不能为空，请在.env文件中设置")
        if not self.neo4j_password:
            raise ValueError("KNOWLEDGE_GRAPH_NEO4J_PASSWORD不能为空，请在.env文件中设置")
        if self.neo4j_uri and not self.neo4j_uri.startswith(('neo4j://', 'neo4j+s://', 'bolt://')):
            raise ValueError("neo4j_uri必须以neo4j://或bolt://开头")
        return self


# 全局配置实例
knowledge_graph_settings = KnowledgeGraphSettings()

def get_knowledge_graph_settings():
    """获取知识图谱配置实例"""
    return knowledge_graph_settings
